#include "standby.h"
#include <QDebug>
#include <QtCore>
#include "camera/platform.h"
/* 休眠功能 */
Standby::Standby()
{
	QSettings settings(PARAM_FILE, QSettings::IniFormat);
	int mainFun = settings.value("Option/Sleep").toInt();
	if(mainFun == 0){
		sleep = 120;
	}else if(mainFun == 1){
		sleep = 300;
	}else if(mainFun == 2){
		sleep = 600;
	}else{
		sleep = 0;
	}
	sleepflag = false;
    QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(sleepUpdate()));
    timer->start(1000);
}

void Standby::sleepUpdate()
{
	sleep--;
	if(sleep == 0){
        if(sleepflag == false){
            set_backlight(0);
            sleepflag = true;
        }
    }
}

//
void Standby::set_StanbyValue(int i)
{
    if(sleepflag == true){
        sleepflag = false;
        set_backlight(180);
    }
    sleep = 0;
}

void Standby::run()
{
    int x[6];
    int y[6];
    int z[6];
    int index = 0;
    int tmp1= 0;
    int pindex[3];
    int nindex[3];

    //initgsensor();
    while(1){
      //  getxyzdata(&x[index], &y[index], &z[index]);
        #if 0
        for (int i = 0; i < 3; i++){
            tmp1 =  index - i;
            if(tmp1 < 0){
                 nindex[i] = 6 + tmp1;
            }else{
                 nindex[i] = tmp1;
            }
           tmp1 =  index + i+1;
           if(tmp1 > 5){
                pindex[i] = tmp1 - 6;
           }else{
               pindex[i] = tmp1;
           }
        }
		if(checkEvent(x, y, z, pindex, nindex) == 1){
            if(sleepflag == true){
                sleep = 0;
                sleepflag = false;
                set_backlight(180);
            }
        }
        index++;
        if(index == 6){
            index = 0;
        }
        #endif
        usleep(300000);
    }
}

void Standby :: set_backlight(int v)
{
    #if 0
    unsigned long args[3];
    int fd = ::open("/dev/disp", O_RDONLY);
    if(fd < 0){
        printf("Open backlight fail\n");
        return;
    }
    args[0]  = 0;
    args[1]  = v;
    args[2]  = 0;
	::ioctl(fd, DISP_CMD_LCD_SET_BRIGHTNESS, args);
    ::close(fd);
    #endif
}

int Standby::checkEvent(int *x, int *y, int *z, int *pindex, int *nindex)
{
    int sumnx = 0;
    int sumny = 0;
    int sumnz = 0;
    int sumpx = 0;
    int sumpy = 0;
    int sumpz = 0;

    int diffx = 0;
    int diffy = 0;
    int diffz = 0;

    for (int i = 0; i < 3; i++){
         sumnx += x[nindex[i]];
         sumny += y[nindex[i]];
         sumnz += z[nindex[i]];

         sumpx += x[pindex[i]];
         sumpy += y[pindex[i]];
         sumpz += z[pindex[i]];
    }
     diffx = sumpx - sumnx;
     diffy = sumpy - sumny;
     diffz = sumpz - sumnz;
     if((diffx > 100) || (diffz > 100)){
         return 1;
     }
     return -1;
}
